<template>
  <div class="comment-container">
    <div class="message-container">
      <div class="message-header">
        <h2>评论管理</h2>
        <el-button 
          type="primary" 
          size="small" 
          @click="markAllAsRead"
          :disabled="unreadCount === 0"
        >
          全部标为已读
        </el-button>
      </div>

      <!-- 评论列表 -->
      <div class="message-list" v-loading="loading">
        <el-empty v-if="!loading && comments.length === 0" description="暂无评论" />
        <template v-else>
          <div 
            v-for="comment in comments" 
            :key="comment.commentId" 
            class="message-item" 
            :class="{ unread: comment.status === 'unread' }"
          >
            <div class="message-content">
              <div class="message-title">
                <span class="dot" v-if="comment.status === 'unread'"></span>
                {{ comment.commenterName }} 
                <span class="article">{{ comment.newsTitle }}</span>
              </div>
              <div class="message-body">{{ comment.commentText }}</div>
              <div class="message-footer">
                <span class="message-time">{{ formatTime(comment.commentTime) }}</span>
                <el-button 
                  v-if="comment.status === 'unread'"
                  type="primary" 
                  link 
                  @click="markAsRead(comment.commentId)"
                >
                  标为已读
                </el-button>
              </div>
            </div>
          </div>
        </template>
      </div>
      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref,onMounted,computed } from 'vue'
import { useUserStore } from '@/store/user'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const comments = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 时间格式化
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 获取评论列表
const fetchComments = async () => {
  if (!userStore.token) return
  
  loading.value = true
  try {
    const response = await axios.get('/app/comments/commentsByUserId', {
      params: {
        userId: userStore.userInfo.id,
        // pageNum: currentPage.value,
        // pageSize: pageSize.value
      }
    })
    
    if (response.data.code === 200) {
      comments.value = response.data.data
      total.value = Array.isArray(response.data.data) 
        ? response.data.data.length 
        : 0
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')
  } finally {
    loading.value = false
  }
}

// 标记单条消息为已读
const markAsRead = async (commentId) => {
  try {
    const response = await axios.post('/app/comments/read', {
      commentId,
      userId: userStore.userInfo.id
    })

    if (response.data.code === 200) {
      const comment = comments.value.find(c => c.commentId === commentId)
      if (comment) {
        comment.status = 'read'
        ElMessage.success('已标记为已读')
      }
    }
  } catch (error) {
    console.error('标记已读失败:', error)
    ElMessage.error('标记已读失败')
  }
}
  // 标记所有评论为已读
const markAllAsRead = async () => {
  try {
    const response = await axios.post('/app/message/readall', {
      userId: userStore.userInfo.id
    })
    
    if (response.data.code === 200) {
      comments.value.forEach(comment => {
        comment.status = 'read'
      })
      ElMessage.success('已全部标记为已读')
    }
  } catch (error) {
    console.error('标记全部已读失败:', error)
    ElMessage.error('标记全部已读失败')
  }
}

// 删除评论
// const handleDelete = (commentId) => {
//   ElMessageBox.confirm('确定删除这条评论吗?', '提示', {
//     confirmButtonText: '确定',
//     cancelButtonText: '取消',
//     type: 'warning'
//   }).then(async () => {
//     try {
//       const response = await axios.delete(`/app/comments/delete/${commentId}`, {
//         // commentId,
//         // userId: userStore.userInfo.id
//       })
      
//       if (response.data.code === 200) {
//         ElMessage.success('删除成功')
//         fetchComments() // 刷新列表
//       }
//     } catch (error) {
//       console.error('删除评论失败:', error)
//       ElMessage.error('删除评论失败')
//     }
//   }).catch(() => {
//     // 用户取消删除
//   })
// }

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchComments()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchComments()
}

// 组件挂载时获取评论
onMounted(() => {
  fetchComments()
})
</script>

<style scoped>
.comment-container {
  padding: 20px;
  min-height: calc(100vh - 60px);
  background-color: #f4f5f6;
  min-height: 100vh;
  /* 添加背景图片 */
  background-image: url("/images/backgroundImages/blueArchive8.jpg"); /* 图片路径 */
  background-size: cover; /* 覆盖整个区域 */
  background-position: center; /* 居中显示 */
  background-repeat: no-repeat; /* 不重复 */
  background-attachment: fixed; /* 固定背景 */
  
}

.message-container {
  max-width: 800px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.message-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.message-list {
  min-height: 300px;
}

.message-item {
  padding: 20px;
  border-bottom: 1px solid #eee;
  transition: background-color 0.3s;
}

.message-item:hover {
  background-color: #f9f9f9;
}

.message-content {
  .message-title {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    
    .username {
      font-weight: bold;
      margin-right: 10px;
    }
    
    .article {
      color: #666;
      font-size: 14px;
    }
  }

  .message-body {
    font-size: 14px;
    color: #333;
    line-height: 1.6;
    margin-bottom: 10px;
    padding-left: 16px;
  }

  .message-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .message-time {
      font-size: 12px;
      color: #999;
    }
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
